package org.example.util.parser;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.example.exception.BusinessException;
import org.example.vo.DocxVo;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

public class DocParser implements ParserInter {
    @Override
    public DocxVo parse(MultipartFile file) {
        // 解析 doc
        String content = StringUtils.EMPTY;
        try (InputStream in = file.getInputStream();
             HWPFDocument doc = new HWPFDocument(in);
             WordExtractor extractor = new WordExtractor(doc);) {
            content = extractor.getText();
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        DocxVo docxVo = new DocxVo();
        docxVo.setTitle(extractTitle(content)); // 可选：提取标题
        docxVo.setContent(cleanContent(content));
        return docxVo;
    }

    private String extractTitle(String content) {
        if (StringUtils.isBlank(content)) return "未命名文档";
        String[] lines = content.split("\\r?\\n");
        for (String line : lines) {
            if (StringUtils.isNotBlank(line) && line.trim().length() > 2) {
                return line.trim();
            }
        }
        return "未命名文档";
    }

    private String cleanContent(String content) {
        return content.replaceAll("\\s{2,}", " ").trim();
    }
}
